<?php
/**
 * Created by zxk7516@foxmail.com  Date: 2017/10/17  Time: 17:15
 */

namespace App\Http\Controllers;


use App\AboutUs;
use App\Article;
use App\Baby;
use App\Course;
use App\CourseSubscribe;
use App\CourseTime;
use App\Events\SendTemplateMsg;
use App\MonthAge;
use App\Town;
use App\WechatUser;
use Carbon\Carbon;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;

class Wechat extends Controller
{
    // 注册成功提醒
    const LOGIN_TEMPLATE_ID = 'KLtdWtyerGq4REsDeQBSMKGVk9GSXg2n8HXP9R40T2U';
    // 审核通过通知
    const VALIDATION_TEMPLATE_ID = 'bghLP-Z6k8z8XLbIw1a8d9s4p4Bu7040uSfnE5Q0v5A';
    // 预约成功提醒
    const  SUBSCRIBES_TEMPLATE_ID = 'TCXtqo_Qlqqu1XiyZkrt5Va2cJEhMz014dWrE_6q-Gg';
    // 申请拒绝通知
    const  REGIST_FAILED_TEMPLATE_ID = '5DDrCSDsy_QAkCiA3LERoh2iGVyOCKxLge-o4mj8rL4';
    // 上课提醒通知
    const COURSE_TIME_REMINDER_TEMPLATE_ID = 'owchO3p2AzyBx6PNJ-YmtK9jf9wDXUGS20q70QJm3oM';



    function regist(Request $request)
    {
        $user = session('wechat.oauth_user');
//            $open_id = $user->getToken()->open_id;
        $open_id = $user->getOriginal()['openid'];
        $nick_name = $user->nickname;
        $wechat_user = WechatUser::firstOrCreate(['open_id' => $open_id], ['nick_name' => $nick_name]);

        if (strtolower($_SERVER['REQUEST_METHOD']) === 'get') {
            $baby = $wechat_user->babies()->first();
            $towns = Town::all();
            if (!empty($baby)) {
                return view('wechat.regist_update', compact('baby', 'towns'));
            }
            return view('wechat.regist', compact('towns'));
        } else {


            $data = $request->all();
            if (isset($data['id'])) {
                $baby = Baby::find($data['id']);
                $first = "资料修改成功";
                if ($baby->state == '2') {
                    $first .= '';
                    $baby->state = 0;
                }
            } else {
                $first = '您已注册成功，请耐心等待审核，审核通过后即可预约课程。操作使用华漕镇计生办管理人员会在两个工作日内以微信的形式通知您。';
                $baby = new Baby();
            }

            $baby->name = $data['name'];
            $baby->birth = $data['birth'];
            $baby->sex = $data['sex'];
            $baby->guardian = $data['guardian'];
            $baby->tel = $data['tel'];
            $baby->habitual_residence = $data['habitual_residence'];
            $baby->town_id = $data['town_id'];
            $baby->wechat_user_id = $wechat_user->id;

//            $baby->state = 1;

            $result = $baby->save();
            $baby_id = $baby->id;

            if ($result && env('APP_ENV') == 'production') {
                //  模板消息，任务队列
                $msg_data = [
                    'first' => $first,
                    'keyword1' => $data['guardian'],
                    'keyword2' => $baby->name,
                    'keyword3' => date('Y-m-d H:i', time()),
                    'remark' => ''
                ];

                event(new SendTemplateMsg(  // TODO 消息通知
                    Wechat::LOGIN_TEMPLATE_ID,
                    $open_id,
                    json_encode($msg_data),
                    '/wx/courses'
                ));
            }
            return compact('result', 'baby_id');
        }
    }

    public function article($id)
    {
        $upload_url = '/uploads/';
        $article = Article::findOrFail($id);

        return view('wechat.article', compact('article', 'upload_url'));
    }


    public function courses()
    {
        $baby_id = session('yuebao.baby_id');
        $baby = Baby::find($baby_id);
        $baby_state = $baby->state;
        $subs = session('yuebao.baby_sub_course_times');
        $birth = $baby['birth'];
        $month_ages = MonthAge::orderBy('start_date', 'desc')->get();
        $baby_month_age = DB::table('month_ages')->where('start_date', '<=', $birth)
            ->where('end_date', '>=', $birth)->first();

        if (isset($_GET['id']) && $_GET['id'] <> '') {
            $current_selecte_monght_age_id = intval($_GET['id']);
        } else if (!empty($baby_month_age)) {
            $current_selecte_monght_age_id = $baby_month_age->id;
        } else {
            $current_selecte_monght_age_id = $month_ages[0]->id;
        }
        $now_str = date('Y-m-d H:i:s', time());
        $course_times_available = CourseTime::whereHas('course', function ($query) use ($current_selecte_monght_age_id) {
            $query->where('month_age_id', '=', $current_selecte_monght_age_id);
        })->where('course_time', '>', $now_str)->orderBy('course_time', 'asc')->get();
//        dd($course_times_available);
        $course_times_past = CourseTime::whereHas('course', function ($query) use ($current_selecte_monght_age_id) {
            $query->where('month_age_id', '=', $current_selecte_monght_age_id);
        })->where('course_time', '<=', $now_str)->orderBy('course_time', 'desc')->get();
        $course_times = $course_times_available->merge($course_times_past);

        foreach ($course_times as $k => $v) {
            $course_times[$k]->course_time = Carbon::createFromFormat('Y-m-d H:i:s', $v->course_time);
        }
        return view('wechat.courses', compact('baby_month_age', 'course_times', 'month_ages', 'current_selecte_monght_age_id', 'subs', 'baby_state'));
    }


    public function subscribes()
    {
        $baby_id = session('yuebao.baby_id');
        $baby = Baby::find($baby_id);
        $subs = $baby->subscribes()->get()->all();

        return view('wechat.subscribes', compact('subs'));
    }

    public function sub(Request $request)
    {

        $baby_id = session('yuebao.baby_id');
        $course_time_id = $request->input('course_time_id');

        $sub_course_times = session('yuebao.baby_sub_course_times', []);
        $sub_count = count($sub_course_times);
        if ($sub_count >= 3) {
            $result = false;
            $msg = '每个宝宝最多可以预约3次课程';
            return compact('result', 'msg');
        }

        // 预约记录
        $baby_sub_course_times = session('yuebao.baby_sub_course_times');
        if (in_array($course_time_id, $baby_sub_course_times)) {
            $result = false;
            $msg = '已经添加过该课程了';
            return compact('result', 'msg');
        }

        // 课时
        $course_time = CourseTime::find($course_time_id);
        $course_name = $course_time->course->name;
        if ($course_time->people_number >= $course_time->max_sub) {
            $result = false;
            $msg = '本课程预约数已经到达上限';
            return compact('result', 'msg');
        } elseif ($course_time->course_time <= date('Y-m-d H:i:s', time())) {
            $result = false;
            $msg = '该课时已经失效';
            return compact('result', 'msg');
        }

        $sub = new  CourseSubscribe();
        $sub->baby_id = $baby_id;
        $sub->course_id = $course_time->course_id;
        $sub->course_time_id = $course_time->id;
        $sub->course_time = $course_time->course_time;
        $sub->save();
        $id = $sub->id;

        $result = $id > 0;
        if ($result) {
            $user = session('wechat.oauth_user');
            $open_id = $user->getOriginal()['openid'];

            // 更新课程预约人数
            $course_time->people_number += 1;
            $course_time->save();
            // 更新本人选择的课程，session

            array_push($baby_sub_course_times, $course_time->id);
            session(['yuebao.baby_sub_course_times' => $baby_sub_course_times]);
            if (env('APP_ENV') == 'production') {
                $msg_data = [
                    'first' => '课程预约成功',
                    'keyword1' => $course_name,
                    'keyword2' => $course_time->course_time, // 预约时间
                    'keyword3' => '上海市闵行区华漕镇繁兴路399弄1号109-C婴智贝佳早教中心', // 办法业条
                    'keyword4' => 3 - ($sub_count + 1), // 办理大厅
                    'keyword5' => date('Y-m-d', time()), // 大厅地址
                    'remark' => '感谢您预约该课程，请按时参加课程'
                ];

                event(new SendTemplateMsg(  // TODO 发送模板消息
                    Wechat::SUBSCRIBES_TEMPLATE_ID,
                    $open_id,
                    json_encode($msg_data),
                    '/wx/courses'
                ));
            }

            $baby = Baby::find($baby_id);
            $guardian = $baby->guardian;
            $baby_name = $baby->name;
            $baby_birth = $baby->birth;
            $course_title = $course_name;
            $month_age = $course_time->course->month_age->title;
            $course_time = $course_time->course_time;
            return compact('result', 'guardian', 'baby_name', 'baby_birth', 'course_title', 'course_time', 'month_age');
        }
        $msg = '发生错误，添加失败';
        return compact('result', 'msg');

    }

    public function courses_intro()
    {
        $baby_id = session('yuebao.baby_id');
        $baby = Baby::find($baby_id);

        $birth = $baby['birth'];
        $month_ages = MonthAge::orderBy('start_date', 'desc')->get();
        $baby_month_age = DB::table('month_ages')->where('start_date', '<=', $birth)
            ->where('end_date', '>=', $birth)->first();
        if (empty($month_ages)) {
            throw new Exception('请加一些月龄数据');
        }
        if (isset($_GET['id']) && $_GET['id'] <> '') {
            $current_selecte_monght_age_id = intval($_GET['id']);
        } else if (!empty($baby_month_age)) {
            $current_selecte_monght_age_id = $baby_month_age->id;
        } else {
            $current_selecte_monght_age_id = $month_ages[0]->id;
        }
        $courses = DB::table('courses')->where('month_age_id', $current_selecte_monght_age_id)->get();
        foreach ($courses as $k => $v) {
            $courses[$k]->description = explode("\n", $v->description);
        }

        $courses_chunk = $courses->chunk(2);

        return view('wechat.courses_intro', compact('courses_chunk', 'month_ages', 'current_selecte_monght_age_id'));
    }

    public function our_teachers()
    {
        $articles = DB::table('articles')->get()->all();
        return view('wechat.our_teachers', compact('articles'));
    }

    public function about()
    {
        $about_us = AboutUs::firstOrCreate(['id' => 1]);
//        dd($about_us);
        return view('wechat.about', compact('about_us'));
    }
}